from docx import Document
from docx.table import Table
from docx.text.paragraph import Paragraph
def clean_cell_text(text):
    return text.replace('\n', ' ').replace('\r', ' ').strip()
def docx_tables_to_markdown_with_line_number(docx_path, output_md_path):
    doc = Document(docx_path)
    body_elements = list(doc.element.body)  # 获取所有段落或表格的底层 XML 元素
    with open(output_md_path, 'w', encoding='utf-8') as f:
        table_count = 0
        para_text_buffer = ""
        para_line_number = 0  # 记录最后一个非空段落的“行号”
        for idx, element in enumerate(body_elements):
            line_number = idx + 1  # 从1开始计行
            if element.tag.endswith('}tbl'):  # 表格
                table = Table(element, doc)
                table_count += 1
                print(f'### 表格 {table_count}（出现在文档第 {line_number} 行，紧跟在下列段落之后）\n\n')
                print(f'> 第 {para_line_number} 行段落内容：{para_text_buffer.strip() or "（空段）"}\n\n')
                f.write(f'### 表格 {table_count}（出现在文档第 {line_number} 行，紧跟在下列段落之后）\n\n')
                f.write(f'> 第 {para_line_number} 行段落内容：{para_text_buffer.strip() or "（空段）"}\n\n')
                # 构造表格 Markdown
                md_lines = []
                for r_idx, row in enumerate(table.rows):
                    cells = [clean_cell_text(cell.text) for cell in row.cells]
                    md_lines.append('| ' + ' | '.join(cells) + ' |')
                    if r_idx == 0:
                        md_lines.append('| ' + ' | '.join(['---'] * len(cells)) + ' |')
                f.write('\n'.join(md_lines))
                f.write('\n\n')
            elif element.tag.endswith('}p'):  # 段落
                para = Paragraph(element, doc)
                text = para.text.strip()
                if text:
                    para_text_buffer = text
                    para_line_number = line_number  # 记录该段落的“行号”
# 示例调用
docx_tables_to_markdown_with_line_number("D:\\hbyt\\AI智能投标\\激励及绩效管理_v1.0_2201.docx", "output2.md")
